package com.hutou.chuangke.activity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bilibili.magicasakura.widgets.TintImageView;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.hutou.chuangke.Bean.FriendBean;
import com.hutou.chuangke.Bean.SoundBean;
import com.hutou.chuangke.MainApplication;
import com.hutou.chuangke.R;
import com.hutou.chuangke.handler.HandlerUtil;
import com.hutou.chuangke.info.MusicInfo;
import com.hutou.chuangke.net.HttpUtil;
import com.hutou.chuangke.net.http.User;
import com.hutou.chuangke.service.MusicPlayer;
import com.hutou.chuangke.uitl.CommonUtils;
import com.hutou.chuangke.uitl.MusicUtils;
import com.hutou.chuangke.widget.CircleImageView;
import com.hutou.chuangke.widget.DividerItemDecoration;
import com.hutou.chuangke.widget.SwipeRefreshLayout;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by o on 2017/5/2.
 * 推荐专辑列表
 */
public class IndexRecommendActivity extends BaseActivity{
    Toolbar toolbar;
    RecyclerView recyclerviewew;
    Context mContext;
    SwipeRefreshLayout swiperefresh;
    ArrayList<SoundBean> mData = new ArrayList<>();
    private ArrayList<MusicInfo> adapterList = new ArrayList<>();
    private SongAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index_recommends);
        mContext = IndexRecommendActivity.this;
        initView();
    }

    private void initView() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setPadding(0, CommonUtils.getStatusHeight(mContext), 0, 0);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setHomeAsUpIndicator(R.drawable.actionbar_back);
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setTitle("");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
//        showQuickControl(false);
        recyclerviewew = (RecyclerView) findViewById(R.id.recyclerviewew);
        recyclerviewew.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerviewew.addItemDecoration(new DividerItemDecoration(mContext,DividerItemDecoration.VERTICAL_LIST));
        adapter = new SongAdapter();
        recyclerviewew.setAdapter(adapter);
        swiperefresh = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
//        swiperefresh.setHeaderView(crateHeadview());
//        swiperefresh.setFooterView(crateHeadview());
        swiperefresh.setOnPullRefreshListener(new SwipeRefreshLayout.OnPullRefreshListener() {
            @Override
            public void onRefresh() {
                swiperefresh.setRefreshing(true);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swiperefresh.setRefreshing(false);
                    }
                },2000);
            }

            @Override
            public void onPullDistance(int distance) {}

            @Override
            public void onPullEnable(boolean enable) {}
        });

        swiperefresh.setOnPushLoadMoreListener(new SwipeRefreshLayout.OnPushLoadMoreListener() {
            @Override
            public void onLoadMore() {
                swiperefresh.setLoadMore(true);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swiperefresh.setLoadMore(false);
                    }
                },2000);
            }

            @Override
            public void onPushDistance(int distance) {

            }

            @Override
            public void onPushEnable(boolean enable) {

            }
        });
        loadData();
    }

    private void loadData(){
        new AsyncTask<Void,Void,Integer>(){

            @Override
            protected Integer doInBackground(Void... voids) {
                int msg = 0;
                try{
                    JsonObject jsonObject = HttpUtil.getResposeJsonObject(User.getMoreSonglist(1,20)
                            ,mContext,false);
                    JsonArray sounds = jsonObject.get("soundlist").getAsJsonArray();
                    for(JsonElement element : sounds){
                        mData.add(MainApplication.gsonInstance().fromJson(element, SoundBean.class));
                    }
                    for(SoundBean soundBean : mData) {
                        MusicInfo musicInfo = new MusicInfo();
                        musicInfo.songId = Integer.parseInt(soundBean.getId());
                        musicInfo.musicName = soundBean.getSoundname();
                        musicInfo.artist = soundBean.getSinger();
                        musicInfo.islocal = false;
                        musicInfo.albumName = "未知";
                        musicInfo.albumId = 2;
                        musicInfo.artistId = Long.valueOf(soundBean.getUserid());
                        musicInfo.lrc = soundBean.getLyric();
                        musicInfo.albumData = soundBean.getSoundurlimg();
                        adapterList.add(musicInfo);
                    }

                }catch(Exception e){
                    e.printStackTrace();
                    return 0;
                }
                return msg;
            }

            @Override
            protected void onPostExecute(Integer msg) {
                super.onPostExecute(msg);
                adapter.setData(adapterList);
                adapter.notifyDataSetChanged();
            }
        }.execute();

    }

    Handler handler = new Handler();

    public interface OnItemClickListener{
        void onItemClick(View view,int position);
    }

    class SongAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
        final static int FIRST_ITEM = 0;
        final static int ITEM = 1;
        List<MusicInfo> mList;
//        private OnItemClickListener mOnItemClickListener;
//        public void setonItemListener(OnItemClickListener mOnItemClickListener){
//            this.mOnItemClickListener = mOnItemClickListener;
//        }
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            if (viewType == FIRST_ITEM) {
                return new CommonItemViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.common_item, viewGroup, false));
            } else {
                return new ListItemViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_musci_common_item, viewGroup, false));
            }
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof CommonItemViewHolder) {
                ((CommonItemViewHolder) holder).textView.setText("共" + mList.size() + "首");
            }
            if (holder instanceof ListItemViewHolder) {
                MusicInfo musicInfo = mList.get(position - 1);
                ((ListItemViewHolder) holder).mainTitle.setText(musicInfo.musicName);
                ((ListItemViewHolder) holder).title.setText(musicInfo.artist);
            }
        }

        public void setData(ArrayList<MusicInfo> mData){
            this.mList = mData;
        }

        @Override
        public int getItemViewType(int position) {
            return position == FIRST_ITEM ? FIRST_ITEM : ITEM;
        }

        @Override
        public int getItemCount() {
            return (null != mList ? mList.size() + 1 : 0);
        }


        class CommonItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
            TextView textView;
            ImageView select;
            public CommonItemViewHolder(View view) {
                super(view);
                this.textView = (TextView) view.findViewById(R.id.play_all_number);
                this.select = (ImageView) view.findViewById(R.id.select);
                view.setOnClickListener(this);
            }
            //播放文件夹
            @Override
            public void onClick(View v) {
                HandlerUtil.getInstance(mContext).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        long[] list = new long[mList.size()];
                        HashMap<Long, MusicInfo> infos = new HashMap();
                        for (int i = 0; i < mList.size(); i++) {
                            MusicInfo info = mList.get(i);
                            list[i] = info.songId;
//                            info.islocal = true;
//                            info.albumData = MusicUtils.getAlbumArtUri(info.albumId) + "";
                            infos.put(list[i], mList.get(i));
                        }
                        MusicPlayer.playAll(infos, list, 0, false);
                    }
                },70);
            }
        }

        class ListItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            ImageView moreOverflow;
            TextView mainTitle, title;
            TintImageView playState;

            public ListItemViewHolder(View view) {
                super(view);
                this.mainTitle = (TextView) view.findViewById(R.id.viewpager_list_toptext);
                this.title = (TextView) view.findViewById(R.id.viewpager_list_bottom_text);
                this.playState = (TintImageView) view.findViewById(R.id.play_state);
                this.moreOverflow = (ImageView) view.findViewById(R.id.viewpager_list_button);
                view.setOnClickListener(this);
            }

            //播放歌曲
            @Override
            public void onClick(View v) {
                HandlerUtil.getInstance(mContext).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        long[] list = new long[mList.size()];
                        HashMap<Long, MusicInfo> infos = new HashMap();
                        for (int i = 0; i < mList.size(); i++) {
                            MusicInfo info = mList.get(i);
                            list[i] = info.songId;
//                            info.islocal = false;
//                            info.albumData = MusicUtils.getAlbumArtUri(info.albumId) + "";
                            infos.put(list[i], mList.get(i));
                        }
                        if (getAdapterPosition() > 0)
                            MusicPlayer.playAll(infos, list, getAdapterPosition() - 1, false);
                    }
                }, 60);
            }
        }
    }
}
